package com.demo.arch.datapulsedemo.v2_pipeline.steps;

import com.demo.arch.datapulsedemo.common.NotificationRecipient;
import com.demo.arch.datapulsedemo.common.NotificationRecipientMapper;
import com.demo.arch.datapulsedemo.common.OrderData;
import com.demo.arch.datapulsedemo.v2_pipeline.core.PipelineContext;
import com.demo.arch.datapulsedemo.v2_pipeline.core.StepExecutionException;
import com.demo.arch.datapulsedemo.v2_pipeline.core.StepHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 步骤3：收件人查询处理器
 * 
 * 职责：
 * - 根据报表类型和数据内容查询接收人
 * - 将接收人列表保存到Context中
 * 
 * @author DataPulse Team
 */
@Slf4j
@Component
public class RecipientQueryStepHandler implements StepHandler {

  @Autowired
  private NotificationRecipientMapper recipientMapper;

  @Override
  public String getName() {
    return "收件人查询";
  }

  @Override
  public int getOrder() {
    return 3;
  }

  @Override
  public void handle(PipelineContext context) throws StepExecutionException {
    log.info(">>> [{}] 开始执行", getName());

    try {
      String reportType = context.getReportType();
      List<OrderData> orderData = context.getOrderData();

      // 查询接收人
      List<NotificationRecipient> recipients = recipientMapper.selectByReportTypeAndData(reportType, orderData);

      // 保存到Context
      context.setRecipients(recipients);

      log.info(">>> [{}] 完成，共查询到 {} 人", getName(), recipients.size());

      // 打印接收人信息
      for (NotificationRecipient recipient : recipients) {
        log.info("  {} ({}) - {} [{}]",
            recipient.getName(),
            recipient.getRole(),
            recipient.getEmail(),
            recipient.getType().getDescription());
      }

    } catch (Exception e) {
      log.error(">>> [{}] 执行失败", getName(), e);
      throw new StepExecutionException(getName(), "收件人查询失败", e);
    }
  }

  @Override
  public boolean shouldExecute(PipelineContext context) {
    // 幂等性检查：如果接收人已存在，跳过执行
    if (context.getRecipients() != null && !context.getRecipients().isEmpty()) {
      log.info(">>> [{}] 接收人已存在，跳过执行", getName());
      return false;
    }
    return true;
  }
}
